package cn.bigfire.wzdj.frame;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class UserPanel extends JPanel {
    private static final Logger log = LoggerFactory.getLogger(UserPanel.class);
    private JLabel avatarLabel;
    private JLabel nameLabel;

    public UserPanel(String avatarPath, String name) {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(128, 178));
        avatarLabel = new JLabel();
        nameLabel = new JLabel(name, SwingConstants.CENTER);

        add(avatarLabel, BorderLayout.NORTH);
        add(nameLabel, BorderLayout.CENTER);

        loadAvatar(avatarPath);
    }

    private void loadAvatar(String avatarPath) {
        new Thread(() -> {
            try {
                BufferedImage avatarImage = null;
                // Check if it's a URL or a file path
                if (avatarPath.startsWith("http://") || avatarPath.startsWith("https://")) {
                    URL url = new URL(avatarPath);
                    avatarImage = ImageIO.read(url);
                } else {
                    File file = new File(avatarPath);
                    avatarImage = ImageIO.read(file);
                }
                if (avatarImage != null) {
                    ImageIcon avatarIcon = new ImageIcon(avatarImage);
                    avatarLabel.setIcon(avatarIcon);

                    // Optionally resize the avatar to fit the panel
                    int avatarSize = 100; // example size
                    Image resizedImage = avatarIcon.getImage().getScaledInstance(avatarSize, avatarSize, Image.SCALE_SMOOTH);
                    avatarLabel.setIcon(new ImageIcon(resizedImage));
                } else {
                    log.error("Failed to load avatar image.");
                }
            } catch (IOException e) {
                log.error("Error loading avatar: " + e.getMessage());
                e.printStackTrace();
            }
            // Update the UI after loading the image
            SwingUtilities.invokeLater(() -> {
                revalidate();
                repaint();
            });
        }).start();
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("User Panel Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);

        // Example usage
//        String avatarPath = "https://example.com/path/to/avatar.png"; // or "C:/path/to/avatar.jpg"
        String avatarPath = "D:\\desktop\\resource\\a.png"; // or "C:/path/to/avatar.jpg"
        String userName = "大火yzs";

        UserPanel userPanel = new UserPanel(avatarPath, userName);
        frame.add(userPanel);

        frame.setVisible(true);
    }
}
